package com.ddzh.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ddzh.cst.SysConst;
import org.codehaus.jettison.json.JSONObject;

import java.util.Random;

public class SMSUtil {
//AccessKey ID LTAI4G3X3orEs83545VQ2UXP
//AccessKey Secret 9vtL4wOWYWVPVvCCddfEBOXgMIvmqe
//    private static final String accessKeyId = "LTAI4G3X3orEs83545VQ2UXP";
//
//    private static final String accessSecret = "9vtL4wOWYWVPVvCCddfEBOXgMIvmqe";

    public static String sendSmsCode(String telephone){
        DefaultProfile profile = DefaultProfile.getProfile(SysConst.REGIONID, SysConst.ACCESSKEYID, SysConst.ACCESSSECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //设置短信内容
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", SysConst.REGIONID);
        //手机号
        request.putQueryParameter("PhoneNumbers", telephone);
        //签名
        request.putQueryParameter("SignName", SysConst.SIGNNAME);
        //短信验证码模板
        request.putQueryParameter("TemplateCode", SysConst.SMS_VALIFYCODE_TEMPLATECODE);
        //CODE_BIT 验证码位数
        String code = generatorCode(SysConst.CODE_BIT);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            //转json格式
            JSONObject jsonObject = new JSONObject(response.getData());
            String res = (String) jsonObject.get("Code");
            System.out.println("res = " + res);//OK
            if("ok".equalsIgnoreCase(res)){
                return code;
            }
//            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 4位或者6位
     * @param num 生成的验证码的位数
     * */
    private static String generatorCode(Integer num){
        //方法二:问题，生成的验证码没有 0 开头的，优点：效率高
        if (num==null || (num!=4 && num!=6)){
            throw new RuntimeException("必须是4位或6位");
        }
        //4位：1000 - 9999
        Random random = new Random();
        if (num==4){
            return String.valueOf(random.nextInt(9000) + 1000);//0-8999 + 1000
        }else{
            return String.valueOf(random.nextInt(900000) + 100000);//0-8999 + 1000
        }
         /*方法1：缺点：用StringBuilder进行字符串拼接，性能低==》可以直接用Integer加，然后再转为String
        Random random = new Random();//如果种子固定，每次产生的随机数顺序是相同的，所以不用种子
        String code="";
        for (Integer i = 0; i < num; i++) {
            code = random.nextInt(10) + code;
        }
        System.out.println("code = " + code);
        return code;*/
    }

}
